import logging
import allure
import requests
from utils.slow_api_write_csv import ApiLogger
import threading


class HttpRequester(object):
    def __init__(self, timeout=3):
        self.__timeout = timeout
        self.__api_logger = ApiLogger()

    def __log_slow_api_async(self, res, request_data, response):
        """
        异步写入慢接口
        :param res: 返回结果
        :param request_data:请求参数
        :param response:
        :return:
        """
        def log():
            self.__api_logger.log_request(res.url, request_data["method"], request_data.get("params"), request_data.get("data"),
                                          request_data.get("json"), response.get("response_time"))

        threading.Thread(target=log).start()


    @allure.step("2. 发送HTTP请求")
    def send_request(self, **request_data):
        """提高给外部调用发起请求的方法"""
        return self.__send_request(**request_data)

    def __send_request(self, **request_data):
        """发起请求的详细逻辑"""

        requited_field = ["method", "url"]
        if not all(field in request_data for field in requited_field):
            raise ValueError(f"http请求缺少必传的参数{requited_field}")

        # 把默认超时时间加入到请求的参数字典中去
        request_data.setdefault("timeout", self.__timeout)

        try:
            res = requests.request(**request_data)

            # with requests.Session() as session:
            #     res = session.request(**request_data)

        except requests.RequestException as e:
            logging.error(f"HTTP请求失败，异常是：{e}")
            logging.error(f"HTTP请求失败，参数是：{request_data}")
            return {"error": str(e)}
        except Exception as e:
            logging.error(f"发生位置错误：{e}")
            return {"error": str(e)}
        else:

            # 判断返回值是否是json
            try:
                data = res.json()
            except ValueError:
                data = res.text
            response = {
                "status_code": res.status_code,
                "json_data": data,
                "response_time": res.elapsed.total_seconds() * 1000
            }

            # 写入慢接口
            # self.__api_logger.log_request(res.url, request_data["method"], request_data["params"], request_data["data"], request_data["json"], response["response_time"])

            # 异步写入慢接口
            self.__log_slow_api_async(res, request_data, response)

            logging.info(f"2. 发送HTTP请求，响应内容: {response}")
            return response

# 通过装饰器简化调用
# def http_request_wrapper(func):
#     def wrapper(*args, **kwargs):
#         data = func(*args, **kwargs)
#         return HttpRequester().send_request(**data)
#     return wrapper


